package com.lhkj.ct.admin.modules.psychology.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.lhkj.ct.base.annntation.Log;
import com.lhkj.ct.base.annntation.PreventDuplicateSubmit;
import com.lhkj.ct.base.config.FileServerConfig;
import com.lhkj.ct.base.enums.ActionType;
import com.lhkj.ct.base.enums.ReturnStatus;
import com.lhkj.ct.base.exception.BusinessException;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.model.ro.ActionResult;
import com.lhkj.ct.base.utils.file.FileUtils;
import com.lhkj.ct.meta.modules.gauge.model.entity.TblScale;
import com.lhkj.ct.meta.modules.gauge.service.ScaleConfigService;
import com.lhkj.ct.meta.modules.psychology.model.entity.TblScalePsyImport;
import com.lhkj.ct.meta.modules.psychology.service.ScalePsyImportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 *
 *<p>
 *     测验导入
 *</p>
 */
@RestController
@RequestMapping("api/plat/psychology/import")
@Api(tags = {"2.6测验导入"})
public class PsyImportController {

    private static Logger logger = LoggerFactory.getLogger(PsyImportController.class);


    @Resource
    private ScalePsyImportService psyImportService;

    @Resource
    private ScaleConfigService scaleConfigService;

    @ApiOperationSupport()
    @ApiOperation(value = "导入记录")
    @GetMapping("list")
    public ActionResult<IPage<TblScalePsyImport>> list(TblScalePsyImport psyImport, PageQuery pageQuery) {
        return ActionResult.success(psyImportService.selectImportPage(psyImport, pageQuery));
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "量表列表", notes = "按量表分类进行分组")
    @GetMapping("scales")
    public ActionResult<List<Map<String, List<Map<String, Object>>>>> scales(TblScale scale) {
        return ActionResult.success(scaleConfigService.groupByCategory(scale));
    }

    @ApiOperation(value = "导出测验量表", produces = "application/octet-stream")
    @ApiOperationSupport(order = 2)
    @PreventDuplicateSubmit
    @PostMapping(value = "export",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @Log(title = "测验导出", actionType = ActionType.EXPORT, isSaveResponseData = false)
    public void export(@RequestBody List<String> ids) {
        psyImportService.export(ids);
    }

    @ApiOperationSupport(order = 3)
    @PostMapping(value = "import")
    @ApiOperation(value = "测验导入")
    @Log(title = "测验导入", actionType = ActionType.IMPORT, isSaveRequestData = false)
    public ActionResult<Void> importTest(@RequestParam("file") MultipartFile file) {
        psyImportService.importPsy(file);
        return ActionResult.success();
    }

    @ApiOperationSupport(order = 3)
    @PostMapping(value = "{id}/download")
    @ApiOperation(value = "下载文件")
    @Log(title = "测验导入", actionType = ActionType.EXPORT, isSaveResponseData = false)
    public void download(@PathVariable String id, HttpServletResponse response) {
        TblScalePsyImport byId = psyImportService.getById(id);
        if (StringUtils.isNotBlank(byId.getFileUrl())) {
            try {
                String fileName = FileUtils.getName(byId.getFileUrl());
                String filePath = byId.getFileUrl().replace(FileServerConfig.getResourcePrefix(), FileServerConfig.getProfile());
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, fileName);
                FileUtils.writeBytes(filePath, response.getOutputStream());
                return;
            } catch (Exception e) {
                logger.error("下载文件失败", e);
                throw new BusinessException(ReturnStatus.SC_INTERNAL_SERVER_ERROR, "文件下载失败！");
            }
        }
        throw new BusinessException(ReturnStatus.SC_NOT_FOUND, "文件不存在或已被删除！");
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "删除记录")
    @DeleteMapping("delete")
    @Log(title = "测验导入", actionType = ActionType.DELETE)
    public ActionResult<Void> delete(@RequestBody List<String> ids) {
        int count = psyImportService.removeByIds(ids);
        return ActionResult.success(String.format("操作成功，共删[%d]条记录", count));
    }

}
